﻿using Honest.MES.Contracts.Interfaces;
using Prism.Events;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;

namespace Honest.MES.Contracts.Services
{
    public class ServiceModuleLoader
    {
        private readonly IEventAggregator _eventAggregator;
        private readonly List<IServiceBase> _loadedServices = new List<IServiceBase>();

        public IReadOnlyCollection<IServiceBase> LoadedServices => _loadedServices.AsReadOnly();

        public ServiceModuleLoader(IEventAggregator eventAggregator)
        {
            _eventAggregator = eventAggregator;
        }

        /// <summary>
        /// 扫描 Services/ 目录并加载所有实现 IServiceBase 的服务
        /// </summary>
        public void LoadServices(string servicesDirectory = "Services")
        {
            if (!Directory.Exists(servicesDirectory))
            {
                Directory.CreateDirectory(servicesDirectory);
                Console.WriteLine($"[ServiceLoader] 创建目录: {servicesDirectory}");
                return;
            }

            var dllFiles = Directory.GetFiles(servicesDirectory, "*.dll", SearchOption.TopDirectoryOnly);

            Console.WriteLine($"[ServiceLoader] 发现 {dllFiles.Length} 个 DLL 文件");

            foreach (var dllPath in dllFiles)
            {
                try
                {
                    // 使用 AssemblyLoadContext 避免锁文件（可选高级功能）
                    var assembly = Assembly.LoadFrom(dllPath);
                    LoadServicesFromAssembly(assembly);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"[ServiceLoader] 加载 DLL 失败: {dllPath} | {ex.Message}");
                }
            }
        }

        private void LoadServicesFromAssembly(Assembly assembly)
        {
            var serviceTypes = assembly.GetTypes()
                .Where(t => typeof(IServiceBase).IsAssignableFrom(t) && !t.IsInterface && !t.IsAbstract)
                .ToList();

            foreach (var type in serviceTypes)
            {
                try
                {
                    // 使用 DI 容器创建实例（推荐）
                    // 如果暂时没有注册，先尝试无参构造
                    var service = Activator.CreateInstance(type) as IServiceBase;

                    if (service != null)
                    {
                        _loadedServices.Add(service);
                        Console.WriteLine($"[ServiceLoader] 成功加载服务: {service.Name} (v{service.Version})");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"[ServiceLoader] 实例化服务失败: {type.FullName} | {ex.Message}");
                }
            }
        }

        /// <summary>
        /// 获取所有已加载的服务，可用于注入到 ServiceManager
        /// </summary>
        public IEnumerable<IServiceBase> GetServices() => _loadedServices;
    }
}